'use strict';

const xhr = new XMLHttpRequest();
const date = new Date();

//上传时间
class SubmitTime {
    time() {
        if (date.getMinutes() < 10) {
            this.M = '0' + date.getMinutes();
        } else {
            this.M = date.getMinutes();
        }
        let sT = `${date.getFullYear()}/${date.getMonth() + 1}/${date.getDate()}--${date.getHours()}:${this.M}`;
        return sT;
    }
}

const st = new SubmitTime();

//获取元素与数据并初始化事件
class GetElements {
    constructor() {
        this.loading = document.querySelector('.loading');
        this.article = document.querySelector('#article');
        this.demo = document.querySelector('#demo');
        this.word = document.querySelector('#word');
        this.picture = document.querySelector('#picture');
        this.create = document.querySelector('#create');
        this.picSubmit = document.querySelector('#pic_submit');
        this.section = document.querySelector('section');
        this.picWrap = document.querySelector('.pic_wrap');
        this.uploadWrap = document.querySelector('.upload_wrap');
        this.picUploadWrap = document.querySelector('.pic_upload_wrap');
        this.ok = document.querySelector('.ok');
        this.no = document.querySelector('.no');
        this.ok2 = document.querySelector('.ok2');
        this.no2 = document.querySelector('.no2');
        this.title = document.querySelector('#title');
        this.id = document.querySelector('#id');
        this.id2 = document.querySelector('#id2');
        this.pic = document.querySelector('#pic');
        this.pic2 = document.querySelector('#pic2');
        this.context = document.querySelector('#context');
        this.aHref = document.querySelector('#a_href');
        this.classN = document.querySelector('#class_name');
        this.classN2 = document.querySelectorAll('.classN');
    }

    initial() {
        for (let i = 0; i < this.classN2.length; i++) {
            this.classN2[i].addEventListener('change', () => {
                this.flag = this.classN2[i].value;
                this.picture.onclick = this.reqPic.bind(this, this.flag);
            })
        }
        this.article.onclick = this.reqArticle.bind(this, 'article');
        this.demo.onclick = this.reqArticle.bind(this, 'demo');
        this.word.onclick = this.reqArticle.bind(this, 'word');
        this.picture.onclick = this.reqPic.bind(this, this.flag);
    }

    reqArticle(who) {
        this.loading.style.display = 'block';
        this.picWrap.style.display = 'none';
        this.picSubmit.style.display = 'none';
        this.section.style.display = 'block';
        this.create.style.display = 'block';
        this.create.setAttribute('data-who', who);
        if (who === 'article') {
            this.article.style.backgroundColor = 'black';
            this.article.style.color = 'rgb(255, 255, 255)';
            this.demo.style.backgroundColor = '';
            this.demo.style.color = '';
            this.word.style.backgroundColor = '';
            this.word.style.color = '';
            this.picture.style.backgroundColor = '';
            this.picture.style.color = '';
        } else if (who === 'demo') {
            this.article.style.backgroundColor = '';
            this.article.style.color = '';
            this.demo.style.backgroundColor = 'black';
            this.demo.style.color = 'rgb(255, 255, 255)';
            this.word.style.backgroundColor = '';
            this.word.style.color = '';
            this.picture.style.backgroundColor = '';
            this.picture.style.color = '';
        } else if (who === 'word') {
            this.article.style.backgroundColor = '';
            this.article.style.color = '';
            this.demo.style.backgroundColor = '';
            this.demo.style.color = '';
            this.word.style.backgroundColor = 'black';
            this.word.style.color = 'rgb(255, 255, 255)';
            this.picture.style.backgroundColor = '';
            this.picture.style.color = '';
        }
        this.myPromise = new Promise((resolve, reject) => {
            this.section.innerHTML = '';
            this.worker = new Worker('/src/js/adminRequest.js');
            this.worker.postMessage(who);
            this.worker.onmessage = (e) => {
                this.section.innerHTML = e.data;
                this.worker.terminate('/src/js/adminRequest.js');
                resolve();
            }
        })
        this.myPromise.then((value) => {
            delAr.delData();
            this.loading.style.display = 'none';
        }).catch((reason) => {
            console.error(reason);
        })
    }

    reqPic(flag) {
        if (!flag) {
            alert('请选择图片类型！');
            return;
        }
        this.loading.style.display = 'block';
        this.create.style.display = 'none';
        this.section.style.display = 'none';
        this.picWrap.style.display = 'flex';
        this.picSubmit.style.display = 'block';
        this.picture.style.backgroundColor = 'black';
        this.picture.style.color = 'rgb(255, 255, 255)';
        this.article.style.backgroundColor = '';
        this.article.style.color = '';
        this.demo.style.backgroundColor = '';
        this.demo.style.color = '';
        this.word.style.backgroundColor = '';
        this.word.style.color = '';
        this.myPromise = new Promise((resolve, reject) => {
            this.picWrap.innerHTML = '';
            this.worker2 = new Worker('/src/js/adminReqImgs.js');
            this.worker2.postMessage(flag);
            this.worker2.onmessage = (e) => {
                this.picWrap.innerHTML = e.data;
                this.worker2.terminate('/src/js/adminReqImgs.js');
                resolve();
            }
        })
        this.myPromise.then((value) => {
            this.xhr = new XMLHttpRequest();
            this.imgs = document.querySelectorAll('.imgs');
            for (let i = 0; i < this.imgs.length; i++) {
                let classN = this.imgs[i].getAttribute('data-class');
                let name = this.imgs[i].getAttribute('data-name');
                this.xhr.open('get', `/get_pic_file?classN=${classN}&name=${name}`, false);
                this.xhr.send();
                if (this.xhr.readyState === 4 && this.xhr.status === 200) {
                    if (this.xhr.responseText === 'no') {
                        alert('图片加载失败！');
                        return;
                    }
                    this.imgs[i].src = this.xhr.responseText;
                }
            }
            delPictures.delPic();
            this.loading.style.display = 'none';
        }).catch((reason) => {
            console.error(reason);
        })
    }
}

const getEle = new GetElements();
getEle.initial();

//图片上传
class SubmitPictures extends GetElements {
    submitPicBoxBlock() {
        this.picSubmit.addEventListener('click', () => {
            this.picUploadWrap.style.display = 'block';
            this.no2.onclick = () => {
                this.picUploadWrap.style.display = 'none';
            }
        })
    }

    submitPic() {
        this.str = '';
        this.pic2.addEventListener('change', () => {
            this.file = this.pic2.files;
        })
        this.ok2.addEventListener('click', () => {
            if (this.file) {
                for (let i = 0; i < this.file.length; i++) {
                    this.reader = new FileReader();
                    this.reader.readAsDataURL(this.file[i]);
                    this.reader.addEventListener('load', (e) => {
                        this.objData = {
                            id: '',
                            name: this.file[i].name,
                            class: this.classN.value,
                            update: st.time(),
                            imgUrlBase64: e.target.result
                        }
                        xhr.open('post', '/submit_pic', true);
                        xhr.setRequestHeader('Content-Type', 'application/json');
                        xhr.send(JSON.stringify(this.objData));
                        xhr.onreadystatechange = () => {
                            if (xhr.readyState === 4 && xhr.status === 200) {
                                if (xhr.responseText === 'no') {
                                    alert('上传失败！');
                                    return;
                                }
                                alert('上传成功！');
                                setTimeout(() => {
                                    this.picture.click();
                                }, 50)
                            }
                        }
                    })
                }
            }
        })
    }

}

//图片删除
class DelPictures {
    delPic() {
        this.dels = document.querySelectorAll('.del');
        this.xhr = new XMLHttpRequest();
        for (let i = 0; i < this.dels.length; i++) {
            this.dels[i].onclick = () => {
                if (!confirm('是否确定要删除？')) return;
                this.name = this.dels[i].getAttribute('data-name');
                this.classN = this.dels[i].getAttribute('data-class');
                console.log(this.name);
                this.xhr.open('get', `/del_pic?classN=${this.classN}&name=${this.name}`, false);
                this.xhr.send();
                if (this.xhr.readyState === 4 && this.xhr.status === 200) {
                    if (this.xhr.responseText === 'no') {
                        alert('删除失败！');
                        return;
                    }
                    alert('删除成功！');
                    setTimeout(() => {
                        getEle.picture.click();
                    }, 50)
                }
            }
        }
    }
}

const delPictures = new DelPictures();

//日志、demo、留言添加管理
class CreateArticle extends GetElements {
    createBoxBlock() {
        this.create.addEventListener('click', () => {
            this.uploadWrap.style.display = 'block';
            this.no.onclick = () => {
                this.uploadWrap.style.display = 'none';
            }
        })
    }

    createData() {
        this.pic.addEventListener('change', () => {
            this.file = this.pic.files;
        })
        this.ok.addEventListener('click', () => {
            if (!this.id.value) {
                alert('id不能为空！');
                return;
            }
            this.promise = new Promise((resolve, reject) => {
                if (this.file && this.create.getAttribute('data-who') === 'article' || this.create.getAttribute('data-who') === 'demo') {
                    this.reader = new FileReader();
                    this.reader.readAsDataURL(this.file[0]);
                    this.reader.addEventListener('load', (e) => {
                        resolve(e.target.result);
                    })
                } else {
                    resolve('');
                }
            })
            this.promise.then((value) => {
                this.objData = {
                    id: this.id.value,
                    title: this.title.value,
                    context: this.context.value,
                    aHref: `/upload/webDemo/${this.aHref.value}`,
                    imgUrlBase64: value,
                    update: st.time()
                }
                console.log(this.objData);
                xhr.open('post', '/create_' + this.create.getAttribute('data-who'), true);
                xhr.setRequestHeader('Content-Type', 'application/json');
                xhr.send(JSON.stringify(this.objData));
                xhr.onreadystatechange = () => {
                    if (xhr.readyState === 4 && xhr.status === 200) {
                        if (xhr.responseText === 'no') {
                            alert('上传失败！');
                            return;
                        }
                        alert('上传成功！');
                        if (this.create.getAttribute('data-who') === 'article') {
                            setTimeout(() => {
                                this.article.click();
                            }, 0);
                        } else if (this.create.getAttribute('data-who') === 'demo') {
                            setTimeout(() => {
                                this.demo.click();
                            }, 0);
                        } else {
                            setTimeout(() => {
                                this.word.click();
                            }, 0);
                        }
                    }
                }
            }).catch((reason) => {
                console.error(reason);
                alert('请添加图片！');
            })
        })
    }
}

//日志、demo、留言删除管理
class DeleteArticle extends GetElements {
    delData() {
        this.dels = document.querySelectorAll('.del');
        this.ids = document.querySelectorAll('.id');
        for (let i = 0; i < this.dels.length; i++) {
            this.dels[i].onclick = () => {
                if (!confirm('是否确定要删除？')) return;
                this.idData = {
                    id: this.ids[i].getAttribute('data-id')
                }
                console.log(this.idData);
                xhr.open('post', '/del_' + this.create.getAttribute('data-who'), true);
                xhr.setRequestHeader('Content-Type', 'application/json');
                xhr.send(JSON.stringify(this.idData));
                xhr.onreadystatechange = () => {
                    if (xhr.readyState === 4 && xhr.status === 200) {
                        if (xhr.responseText === 'no') {
                            alert('删除失败！');
                            return;
                        }
                        alert('删除成功！');
                        if (this.create.getAttribute('data-who') === 'article') {
                            setTimeout(() => {
                                this.article.click();
                            }, 0);
                        } else if (this.create.getAttribute('data-who') === 'demo') {
                            setTimeout(() => {
                                this.demo.click();
                            }, 0);
                        } else {
                            setTimeout(() => {
                                this.word.click();
                            }, 0);
                        }
                    }
                }
            }
        }
    }
}

new CreateArticle().createBoxBlock();
new SubmitPictures().submitPicBoxBlock();
new SubmitPictures().submitPic();
new CreateArticle().createData();
const delAr = new DeleteArticle();



